package com.ljkj.cordial.chat.widget;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;

import com.ljkj.cordial.chat.R;
import com.nic.view.adapter.CommonAdapter;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SingleCommonAdapter extends CommonAdapter<String> {
    SparseArray<Boolean> checkeds = new SparseArray<>();
    private int selected;

    @Override
    public View getBindView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dialog_single_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String text = (String) getItem(position);
        holder.cb.setText(text);
        holder.cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < checkeds.size(); i++) {
                    checkeds.put(i, false);
                }
                checkeds.put(position, true);
                selected = position;
                notifyDataSetChanged();
            }
        });
        boolean b;
        if (selected == position) {
            b = checkeds.get(position, true);
            if (itemClickListener != null) {
                itemClickListener.onClick(parent, position, text);
            }
        } else {
            b = checkeds.get(position, false);
        }

        if (b) {
            holder.cb.setChecked(true);
        } else {
            holder.cb.setChecked(false);
        }
        return convertView;
    }

    public void setSelected(int position) {
        selected = position;
//        notifyDataSetChanged();
    }

    static class ViewHolder {
        @BindView(R.id.cb)
        CheckedTextView cb;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    private OnSingleItemClickListener itemClickListener;

    public void setItemClickListener(OnSingleItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public interface OnSingleItemClickListener {
        void onClick(View view, int position, String value);
    }
}
